/*
 * Copyright (C) 2008-2010 Oliver Horn.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.funcj.tuples;

import java.io.Serializable;
import java.util.Arrays;

import javax.annotation.concurrent.Immutable;

/**
 * A generic n-tuple.
 * <p>
 * This class is intentionally not public. It serves as generic fallback
 * implementation if {@link Tuples#newTuple(Object...)} is called with more
 * than four elements.
 *
 * @author Oliver Horn
 */
@Immutable
final class NTuple implements Tuple, Serializable {

	private static final long serialVersionUID = -1055969899973723296L;

	private final Object[] elements;

	public NTuple(Object[] elements) {
		this.elements = elements;
	}

	public int arity() {
		return elements.length;
	}

	public Object[] toArray() {
		Object[] array = new Object[elements.length];
		System.arraycopy(elements, 0, array, 0, elements.length);
		return array;
	}

	@Override
	public int hashCode() {
		return Arrays.hashCode(elements);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		if (obj instanceof Tuple) {
			Tuple other = (Tuple) obj;
			return (other.arity() == elements.length) && Arrays.equals(elements, other.toArray());
		}
		return false;
	}

	@Override
	public String toString() {
		int arity = elements.length;
		StringBuilder sb = new StringBuilder();
		sb.append('(');
		for (int i = 0; i < arity; i++) {
			if (i > 0) {
				sb.append(", ");
			}
			sb.append(elements[i]);
		}
		if (arity == 1) {
			sb.append(',');
		}
		sb.append(')');
		return sb.toString();
	}
}
